<!--
 * @Descripttion: 商品选择
 * @version:
 * @Author: cxguo
 * @Date: 2019-10-18 09:21:43
 * @LastEditors: cxguo
 * @LastEditTime: 2020-10-26 14:26:26
 -->
<template>
  <div>
    <!-- $attrs: {{ $attrs }} -->
    <!-- <el-button type="primary" @click="btnTestAdd">增加</el-button>
    <el-button type="primary" @click="btnTestDel">删除</el-button>
    <el-button type="primary" @click="btnTestUpdate">修改</el-button>
    <el-button type="primary" @click="btnTestGetData">获取值</el-button>
    <el-button type="primary" @click="btnTestGetPostData">获取要Post的值</el-button> -->
    <vxe-grid
      ref="table"
      class="simple-select select-table"
      border
      resizable
      highlight-hover-row
      show-footer
      :footer-method="footerMethod"
      :footer-row-class-name="footerRowClassName"
      :mouse-config="{selected: true}"
      :edit-config="{mode:'cell', trigger:'click', activeMethod: activeRowMethod}"
      :columns="columnsData"
      :data="tableData"
      :edit-rules="validRules"
      :loading="loading"
      v-bind="$attrs"
      :keyboard-config="{isArrow: true, isTab: true, isEnter: true, isEdit: true}"
      @edit-closed="onEditClosed"
      @cell-mouseenter="onCellMouseEnter"
      @cell-mouseleave="onCellMouseLeave"
    />
  </div>
</template>
<script>
import { columns, tableApi, onGoodSelect, exportApi } from './mixins'
import { column2emptyObj, sunTableAmount, sumTableAmountFileds } from '@/libs/util.js'
import { tableIndex } from '@/libs/mixins'
import { getUnitOptionsByUnitStr, getGoodsTotalPriceByRow } from './mixins/utils.js'
import layer from '@/views/components/TablePopIframe'
const BLANK_DATA_LEN = 6

export default {
  name: 'GoodsSelected',
  mixins: [columns, tableApi, onGoodSelect, exportApi, tableIndex],
  props: {
    /**
     * simpleSelect的props对象
     */
    simpleSeleProps: {
      type: Object,
      default: () => { return {} }
    },
    /**
     * 是否开启税率
     */
    isOpenTax: {
      type: Boolean,
      default: false
    },
    /**
     * 税率值（%）
     */
    taxRate: {
      type: Number,
      default: 1
    },
    /**
     * 是否设置价格
     */
    isSetPrice: {
      type: Boolean,
      default: true
    },
    /**
     * 是否开启table可编辑
     */
    isTableActive: {
      type: Boolean,
      default: true
    },
    /**
     * 默认给他设置一个x什么类型的价格（比如销售价）
     */
    defaultPriceCat: {
      type: String,
      default: null
    },
    colFields: {
      type: Array,
      default: () => { return null }
    }
  },
  data() {
    return {
      tableComp: null,
      loading: false,
      tableData: [],
      simpleIframe: null,
      dialogVisible: true,
      validRules: {
        skuId: [{ required: true, message: '商品Id必填' }],
        name: [{ required: true, trigger: 'blur', message: '商品名称必填' }],
        code: [{ required: true, message: '商品编号必填' }],
        quantity: [{ required: true, message: '商品数量必填' }],
        unitId: [{ required: true, message: '单位必填' }],
        unitMulti: [{ required: true, message: '单位系数必填' }],
        price: [
          { required: true, message: '单价必填' }
        ],
        total: [{ required: true, message: '金额必填' }]
      }
    }
  },
  computed: {
    columnsData: function() {
      const colFields = this.colFields
      const originColumnsData = this.originColumnsData
      let result = originColumnsData
      if (colFields) {
        result = originColumnsData.filter(item => { return colFields.indexOf(item.field) !== -1 })
      }
      if (this.isOpenTax) {
        const priceIndex = result.findIndex(item => { return item.field === 'total' })
        if (priceIndex !== -1) result.splice(priceIndex + 1, 0, ...this.taxColumnsData)
      }
      return result
    },
    totalMsg: function() {
      const tableData = this.tableData
      const amoungtObj = sumTableAmountFileds(tableData, ['quantity', 'total', 'taxAmount'])
      amoungtObj.num = amoungtObj.quantity
      amoungtObj.price = amoungtObj.total
      return amoungtObj
    }
  },
  watch: {
    tableData: {
      handler(data) {
        this.$refs.table.updateFooter()
        this.updateTableTotalAmount()
      },
      deep: true
    },
    defaultPriceCat: {
      handler(cat) {
        if (!cat) return
        const tableData = this.getTableData()
        tableData.forEach(item => {
          const priceStr = item.priceStr
          if (priceStr) {
            const priceObj = JSON.parse(priceStr)
            const price = priceObj[cat]
            item.price = price
          }
        })
      }
    }
  },
  mounted() {
    this.tableComp = this.$refs.table
    this.initData()
  },
  methods: {
    btnAddTableData() {
      const data = this.getBlankDataList(1)
      this.addTableData(data)
    },
    btnRemoveTableData(row) {
      const tableData = this.getTableData()
      if (tableData.length <= 1) return
      this.delTableData([row])
    },
    btnChooseGoods(params) {
    },
    // api
    initData() {
      this.addTableBlankData(BLANK_DATA_LEN)
    },
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          if (['quantity', 'total', 'taxAmount'].includes(column.property)) {
            return sunTableAmount(data, column.property)
          }
          return null
        })
      ]
    },
    /**
     * 更新table总价
     */
    updateTableTotalAmount() {
      const tableData = this.tableData
      tableData.forEach(item => {
        if (item.skuId) {
          const total = getGoodsTotalPriceByRow(item)
          this.$set(item, 'total', total)
          // 税额
          if (this.isOpenTax) {
            const { taxRate } = item
            const taxAmount = this.$amount((taxRate / 100) * total).format()
            this.$set(item, 'taxAmount', taxAmount)
          }
        }
      })
    },
    addTableBlankData(number) {
      this.tableData = this.getBlankDataList(number)
    },
    getBlankDataList(num) {
      const columnsData = this.columnsData
      const result = []
      for (let i = 0; i < num; i++) {
        result.push(column2emptyObj(columnsData))
      }
      return result
    },
    activeRowMethod(params) {
      const { column, rowIndex, seq, row } = params
      if (column.property === 'unitName') {
        const options = getUnitOptionsByUnitStr(row) || []
        if (options.length > 1) return true
        return false
      }
      const index = rowIndex + 1 || seq
      const b = this.isAllowTableEdit(index)
      return b
    },
    footerRowClassName() {
      return 'bg-gay'
    },
    popGoodSimpleSelect({ container, content, props }) {
      return layer(container, content, props)
    },
    isAllowTableEdit(seq) {
      if (!this.isTableActive) return false
      const tableData = this.getTableData() || []
      const okRows = tableData.filter(item => { return item.skuId })
      const dis = seq - okRows.length
      if (dis <= 1) {
        return true
      }
      return false
    },
    // ON
    onEditClosed(params) {
      this.closeSimpleGoodSelect()
    },
    /**
     * 鼠标移入事件
     * @param {*} param0
     */
    onCellMouseEnter(params) {
      const { row, seq } = params
      this.currentRowIndex = row._XID
      if (this.isAllowTableEdit(seq)) {
        // const { row } = params
        // this.setTableActiveRow(row)
      }
    },
    onCellMouseLeave() {
      this.currentRowIndex = null
    }
  }
}
</script>

